<template>
  <v-card flat class="Quotation-Container">
    <v-row class="header text-left align-start" no-gutters>
      <v-col :cols="3">
        <span class="mr-2 title">Quote</span>
        <v-btn
          @click="openAddQuote"
          class="plus-btn"
          elevation="0"
          color="#D9D9D9"
          fab
          width="32"
          height="32"
        >
          <v-icon color="#626C84">mdi-plus-thick</v-icon>
        </v-btn>
      </v-col>
      <v-col
        v-if="!loadingQuoteDetails && selectedQuote && step !== 6"
        class="ml-4"
        :cols="9"
      >
        <v-row no-gutters class="justify-space-between">
          <v-col class="d-flex">
            <span class="title mr-4">
              {{ selectedQuote.number }}
            </span>
            <v-chip
              :color="selectedQuote.status === 'new' ? '#556282' : '#EB9B31'"
              class="mr-4"
              text-color="#fff"
              x-small
              label
              v-text="selectedQuote.status"
            >
            </v-chip>
            <v-spacer>
              <v-col class="py-0">
                <em>
                  Add by {{ selectedQuote.createName }} @
                  {{ selectedQuote.createDate }}
                </em>
              </v-col>
              <v-col class="py-0">
                <em>
                  Last Modified by {{ selectedQuote.lastModifiedName }} @
                  {{ selectedQuote.lastModifiedDate }}
                </em>
              </v-col>
            </v-spacer>
          </v-col>
          <v-col class="header-action flex-grow-0 d-flex mr-4">
            <v-tooltip bottom>
              <template v-slot:activator="{ on }">
                <v-icon @click="openApprovalMessage" v-on="on" color="#BABABC">
                  mdi-check-circle
                </v-icon>
              </template>
              Approval Message
            </v-tooltip>
            <v-tooltip bottom>
              <template v-slot:activator="{ on }">
                <v-icon @click="openRejectMessage" v-on="on" color="#BABABC">
                  mdi-close-circle
                </v-icon>
              </template>
              Reject Message
            </v-tooltip>
            <v-tooltip bottom>
              <template v-slot:activator="{ on }">
                <v-icon @click="openSendQuoteDialog" v-on="on" color="#BABABC">
                  mdi-send
                </v-icon>
              </template>
              Send Quotation
            </v-tooltip>
            <v-tooltip bottom>
              <template v-slot:activator="{ on }">
                <v-icon @click="openEmailQuoteDialog" v-on="on" color="#BABABC">
                  mdi-email
                </v-icon>
              </template>
              Email Quotation
            </v-tooltip>
          </v-col>
        </v-row>
      </v-col>
    </v-row>
    <v-row class="content" no-gutters>
      <v-col class="QuoteList-wrap" :cols="3">
        <v-skeleton-loader
          v-if="loadingQuoteList"
          type="list-item@9"
        ></v-skeleton-loader>
        <QuoteList
          v-else
          v-model="selectedIndex"
          @openDeleteQuoteDialog="openDeleteQuoteDialog"
          @copyQuote="copyQuote"
          :quoteList="quoteList"
        >
          <template #item="{ item }">
            <v-list-item-content class="py-0">
              <v-list-item-title v-text="item.number"></v-list-item-title>

              <v-list-item-subtitle class="text--primary">
                {{ item.prospect }} - {{ item.prospectName }}
              </v-list-item-subtitle>

              <v-list-item-subtitle
                v-text="item.address"
              ></v-list-item-subtitle>
            </v-list-item-content>

            <v-list-item-action class="my-0">
              <v-list-item-action-text>
                <v-chip
                  text-color="#fff"
                  :color="item.status === 'new' ? '#556282' : '#EB9B31'"
                  x-small
                  label
                  v-text="item.status"
                >
                </v-chip
              ></v-list-item-action-text>

              <!-- <span>A/C Not posted</span> -->

              <span> {{ item.quote }} </span>
            </v-list-item-action>
          </template>
        </QuoteList>
      </v-col>
      <v-col class="QuoteDetails-wrap ml-4" :cols="9">
        <v-skeleton-loader
          v-if="loadingQuoteDetails"
          height="100%"
          tile
          type="list-item@20"
        ></v-skeleton-loader>
        <QuoteDetails
          v-else-if="quoteDetails"
          @add="addQuote"
          @edit="editQuote"
          :step="step"
          :quoteDetails="quoteDetails"
        ></QuoteDetails>
      </v-col>
    </v-row>
    <Dialog v-model="showDialog" :title="dialogTitle" width="480">
      <template #headerAppend="{ close }">
        <v-icon @click="close" small color="#fff" class="icon">
          mdi-close
        </v-icon>
      </template>
      <SendQuote
        @submit="submitToSend"
        :type="sendType"
        v-if="[1, 2].includes(step)"
      ></SendQuote>
      <DeleteQuote
        v-else-if="step === 3 && selectedQuote"
        @delete="deleteQuote"
        :item="selectedQuote"
      ></DeleteQuote>
      <Message
        v-else-if="[4, 5].includes(step)"
        @submit="submitMessage"
        v-model="messageValue"
        :type="messageType"
      ></Message>
    </Dialog>
  </v-card>
</template>
<script lang="ts">
import { Vue, Component, Watch } from "vue-property-decorator";
import QuoteList from "@/components/Quotation/QuoteList/QuoteList.vue";
import QuoteDetails from "@/components/Quotation/QuoteDetails/QuoteDetails.vue";
import Dialog from "@/components/Maintenance/Dialog/Dialog.vue";
import SendQuote from "@/components/Quotation/Dialog/SendQuote.vue";
import DeleteQuote from "@/components/Quotation/Dialog/DeleteQuote.vue";
import Message from "@/components/Quotation/Dialog/Message/Message.vue";
import { getDate, getTime } from "@/common/constants/Utils";
import { IQuote, IQuoteDetails } from "@/components/Quotation/index";
@Component({
  components: {
    QuoteList,
    QuoteDetails,
    Dialog,
    SendQuote,
    DeleteQuote,
    Message,
  },
})
export default class Quotation extends Vue {
  // 1.sendQuote 2.EmailQuote 3.DeleteQuote 4.Approval Message 5.Reject Message 6.addQuote 7.editQuote 8.copyQuote
  step = -1;
  // dialog
  dialogTitle = "";
  showDialog = false;
  openDialog() {
    this.showDialog = true;
  }
  closeDialog() {
    this.showDialog = false;
  }
  // quoteList
  selectedIndex: number | null | undefined = null;
  @Watch("selectedIndex")
  onSelectedIndexChange(index: number | null | undefined) {
    let selectedQuote = null;
    if (typeof index === "number") {
      this.step = 7;
      selectedQuote = this.quoteList[index];
    }
    this.$store.commit("QuotationStore/setQuote", selectedQuote);
  }
  get selectedQuote() {
    return this.$store.state.QuotationStore.quote;
  }
  set selectedQuote(selectedQuote: IQuote | null) {
    this.$store.commit("QuotationStore/setQuote", selectedQuote);
  }

  @Watch("selectedQuote")
  onSelectedQuoteChange(selectedQuote: IQuote | null) {
    // setQuoteDetails
    this.loadingQuoteDetails = true;
    if (selectedQuote) {
      setTimeout(() => {
        this.loadingQuoteDetails = false;
      }, 900);
    } else {
      this.loadingQuoteDetails = false;
    }
  }
  loadingQuoteList = false;
  quoteList: IQuote[] = [];
  getQuoteList() {
    this.loadingQuoteList = true;
    new Promise<Array<IQuote>>((res) => {
      const quoteList: IQuote[] = [
        {
          id: "1",
          number: "Q-22049",
          status: "new",
          prospect: "PP-22015",
          prospectName: "Cafe de Coral",
          address: "New restaurant in TW",
          quote: "3,000.000.00",
          createName: "Candy Wong",
          createDate: "2022-03-02 11:30",
          lastModifiedName: "Tony Ma",
          lastModifiedDate: "2022-04-04 17:43",
          details: {
            id: "1",
            customerName: "Cafe De Coral",
            description: "User Testing",
            amount: "960,000.00",
            cost: "800,000.00",
            gain: "160,000.00",
            retention: 10,
            month: 12,
            jobCate: "Delivery",
            customer: {
              prospect: "PP-22015",
              prospectName: "Cafe de Coral",
              contactPerson: "Mr. Jimmy Wang",
              jobTitle: "Sales Manager",
              email: "jimmy.wang@cafedecoral.com",
              mobile: "9876-7895432",
              work: "8765 4321",
              fax: "1234 5678",
            },
            items: [
              {
                id: "1",
                line: "1.00",
                description: "Group 1 items",
                children: [
                  {
                    id: "1",
                    line: "1.01",
                    description: "Group 1 items 1",
                    supplier: "Advance Tech",
                    unitCost: "65,000.00",
                    unitRate: "78,000.00",
                    qty: "2",
                    totalCost: "130,000.00",
                    totalAmt: "156,000.00",
                    gain: "26,000.00",
                    gp: "20.00%",
                  },
                  {
                    id: "2",
                    line: "1.02",
                    description: "Group 1 items 2",
                    supplier: "Wing Kee",
                    unitCost: "90,000.00",
                    unitRate: "108,000.00",
                    qty: "3",
                    totalCost: "270,000.00",
                    totalAmt: "324,000.00",
                    gain: "54,000.00",
                    gp: "20.00%",
                  },
                ],
              },
            ],
            payment: [
              {
                phases: "1",
                description:
                  "50% of the project total as the deposit for the project",
                percentage: "50%",
              },
              {
                phases: "2",
                description:
                  "Half of the progress of the works to pay 40% of the project total",
                percentage: "40%",
              },
              {
                phases: "3",
                description:
                  "The completion of project to pay 10% of the project total",
                percentage: "10%",
              },
            ],
            termsConditionsList: [
              "12 months defect liability period Of all contract items. The project period is 40 working Days (Sunday, Public Holiday excluded)",
              "With respect tO Minor work submission. all required documents and drawings shall be prepared. and submitted in accordance with latest MWCS that implemented by BD of GOV.",
              "Contractor responsible for keeping public places clean during construction ,packing construction material and leaving in the garbage collection place designated by management office each day. All debris / construction wastes shall be disposed to Waste Disposal.",
              "All amount is the value calculated based on Daytime WOrk. If decoration is progress at night, the item cost will be Doubled as the amount for your reference",
            ],
            attachmentList: [
              {
                id: "1",
                type: "jpeg",
                src: "https://images.pexels.com/photos/1591447/pexels-photo-1591447.jpeg?auto=compress&cs=tinysrgb&w=1600",
                title: "STD202201",
                subtitle: "Inspection Sheet",
              },
              {
                id: "2",
                type: "jpeg",
                src: "https://images.pexels.com/photos/1366919/pexels-photo-1366919.jpeg?auto=compress&cs=tinysrgb&w=1600",
                title: "STD202202",
                subtitle: "Inspection Sheet",
              },
              {
                id: "3",
                type: "jpg",
                src: "https://cdn.pixabay.com/photo/2015/10/30/20/13/sunrise-1014712_960_720.jpg",
                title: "STD202203",
                subtitle: "Inspection Sheet",
              },
              {
                id: "4",
                type: "jpg",
                src: "https://cdn.pixabay.com/photo/2022/10/03/21/47/fog-7496901_960_720.jpg",
                title: "STD202203",
                subtitle: "Inspection Sheet",
              },
              {
                id: "5",
                type: "jpg",
                src: "https://ts1.cn.mm.bing.net/th/id/R-C.40e8a86c22b0e5211b838d35eb3ed2e9?rik=10BkvUtRe%2bUfFA&riu=http%3a%2f%2fwww.ukutu.cn%2fupload%2f201603%2f23%2f201603230207284852.jpg&ehk=u8msuCl9ufjNb919xfDzyz6n%2bfNrpMx6gzFcWxjPXDI%3d&risl=&pid=ImgRaw&r=0",
                title: "STD202203",
                subtitle: "Inspection Sheet",
              },
              {
                id: "6",
                type: "jpg",
                src: "https://ts1.cn.mm.bing.net/th/id/R-C.18c926a5b5b33e6c7ec7938fe79714a6?rik=XROULmNY%2fkPEcQ&riu=http%3a%2f%2fwww.ukutu.cn%2fupload%2f201603%2f23%2f201603230207284857.jpg&ehk=Daa7YSXlRf09mbTzfKuvuRlPY%2fsqG0qDVAZqb%2bvkVB0%3d&risl=&pid=ImgRaw&r=0",
                title: "STD202203",
                subtitle: "Inspection Sheet",
              },
            ],
          },
        },
        {
          id: "2",
          number: "Q-22049",
          status: "quoted",
          prospect: "PP-22016",
          prospectName: "Tai Hing",
          address: "Ma On Shan",
          quote: "4,000.000.00",
          createName: "Candy Wong",
          createDate: "2022-03-02 12:30",
          lastModifiedName: "Tony Ma",
          lastModifiedDate: "2022-04-04 19:43",
          details: {
            id: "5",
            customerName: "Tai Hing",
            description: "User Testing",
            amount: "960,000.00",
            cost: "800,000.00",
            gain: "160,000.00",
            retention: 10,
            month: 12,
            jobCate: "Testing for Cal",
            customer: {
              prospect: "PP-22016",
              prospectName: "Tai Hing",
              contactPerson: "Mr. Jimmy Wang",
              jobTitle: "Sales Manager",
              email: "jimmy.wang@cafedecoral.com",
              mobile: "9876 5432",
              work: "8765 4321",
              fax: "1234 5678",
            },
            items: [
              {
                id: "3",
                line: "1.00",
                description: "Group 1 items",
                children: [
                  {
                    id: "6",
                    line: "1.01",
                    description: "Group 1 items 1",
                    supplier: "Advance Tech",
                    unitCost: "65,000.00",
                    unitRate: "78,000.00",
                    qty: "2",
                    totalCost: "130,000.00",
                    totalAmt: "156,000.00",
                    gain: "26,000.00",
                    gp: "20.00%",
                  },
                  {
                    id: "7",
                    line: "1.02",
                    description: "Group 1 items 2",
                    supplier: "Wing Kee",
                    unitCost: "90,000.00",
                    unitRate: "108,000.00",
                    qty: "3",
                    totalCost: "270,000.00",
                    totalAmt: "324,000.00",
                    gain: "54,000.00",
                    gp: "20.00%",
                  },
                ],
              },
              {
                id: "4",
                line: "2.00",
                description: "Group 2 items",
                children: [
                  {
                    id: "8",
                    line: "2.01",
                    description: "Group 1 items 1",
                    supplier: "Advance Tech",
                    unitCost: "65,000.00",
                    unitRate: "78,000.00",
                    qty: "2",
                    totalCost: "130,000.00",
                    totalAmt: "156,000.00",
                    gain: "26,000.00",
                    gp: "20.00%",
                  },
                ],
              },
            ],
            payment: [
              {
                phases: "1",
                description:
                  "50% of the project total as the deposit for the project",
                percentage: "50%",
              },
              {
                phases: "2",
                description:
                  "Half of the progress of the works to pay 40% of the project total",
                percentage: "40%",
              },
            ],
            termsConditionsList: [
              "12 months defect liability period Of all contract items. The project period is 40 working Days (Sunday, Public Holiday excluded)",
              "With respect tO Minor work submission. all required documents and drawings shall be prepared. and submitted in accordance with latest MWCS that implemented by BD of GOV.",
            ],
            attachmentList: [],
          },
        },
      ];
      setTimeout(() => {
        res(quoteList);
      }, 1000);
    }).then((res) => {
      this.quoteList = res;
      this.loadingQuoteList = false;
    });
  }

  // quoteDetails
  loadingQuoteDetails = false;
  get quoteDetails() {
    if (this.selectedQuote) {
      return this.selectedQuote.details;
    }
    return null;
  }
  // action
  // Quote
  createInitQuote() {
    const quote: IQuote = {
      id: "",
      number: "",
      status: "",
      prospect: "",
      prospectName: "",
      address: "",
      quote: "",
      createName: "",
      createDate: "",
      lastModifiedName: "",
      lastModifiedDate: "",
      details: {
        id: "",
        customerName: "",
        description: "",
        amount: "",
        cost: "",
        gain: "",
        retention: 10,
        month: new Date().getMonth() + 1,
        jobCate: "",
        customer: {
          prospect: "",
          prospectName: "",
          contactPerson: "",
          jobTitle: "",
          email: "",
          mobile: "",
          work: "",
          fax: "",
        },
        items: [],
        payment: [],
        termsConditionsList: [],
        attachmentList: [],
      },
    };
    return quote;
  }

  openAddQuote() {
    this.selectedIndex = undefined;
    this.$nextTick(() => {
      this.$store.commit("QuotationStore/setQuote", this.createInitQuote());
      this.step = 6;
    });
  }
  sendType = "";
  openSendQuoteDialog() {
    this.step = 1;
    this.sendType = "Send";
    this.dialogTitle = "Send";
    this.openDialog();
  }

  openEmailQuoteDialog() {
    this.step = 2;
    this.sendType = "Email";
    this.dialogTitle = "Email Quotation";
    this.openDialog();
  }

  submitToSend() {
    this.sendType = "";
    this.closeDialog();
    this.$Swal.fire({
      position: "center",
      icon: "success",
      title: "success",
      showConfirmButton: false,
      timer: 1500,
    });
    this.closeDialog();
  }

  openDeleteQuoteDialog() {
    this.step = 3;
    this.dialogTitle = "Delete";
    this.openDialog();
  }

  addQuote(quoteDetails: IQuoteDetails) {
    const quote = this.selectedQuote as IQuote;
    const currentName = this.$store.state.AuthenticationStore.userName;
    const currentDate = `${getDate("-")} ${getTime(":")}`;
    // initQuote
    if (this.step === 6) {
      quote.number = "Q-" + String(new Date().getTime());
      quote.status = "new";
      quote.address = "null";
    }
    quote.id = String(new Date().getTime());
    quote.createDate = currentDate;
    quote.createName = currentName;
    quote.lastModifiedDate = currentDate;
    quote.lastModifiedName = currentName;
    quote.prospect = quoteDetails.customer.prospect;
    quote.prospectName = quoteDetails.customer.prospectName;
    quote.prospectName = quoteDetails.customer.prospectName;
    quote.quote = quoteDetails.amount;
    quote.details = quoteDetails;
    const length = this.quoteList.push(quote);
    if (this.step === 8) {
      this.selectedIndex = length - 1;
    }
    this.step = -1;
  }

  deleteQuote(quote: IQuote) {
    const index = this.quoteList.findIndex((item) => item.id === quote.id);
    this.quoteList.splice(index, 1);
    if (this.quoteList.length === 0) {
      this.selectedIndex = null;
    }
    this.closeDialog();
  }

  copyQuote() {
    const copyQuoteInfo = JSON.parse(
      JSON.stringify(this.quoteList[this.selectedIndex as number])
    );
    copyQuoteInfo.id = String(new Date().getTime());
    copyQuoteInfo.details.id = String(new Date().getTime());
    this.selectedIndex = null;
    this.step = 8;
    this.$nextTick(() => {
      this.$store.commit("QuotationStore/setQuote", copyQuoteInfo);
    });
  }

  editQuote(quoteDetails: IQuoteDetails) {
    (this.quoteList as IQuote[]).some((quote) => {
      if (quote.details.id === quoteDetails.id) {
        quote.lastModifiedDate = `${getDate("-")} ${getTime(":")}`;
        quote.lastModifiedName = this.$store.state.AuthenticationStore.userName;
        Object.assign(quote.details, quoteDetails);
        return true;
      }
      return false;
    });
  }

  // message
  messageType = "";
  messageValue = "";
  openApprovalMessage() {
    this.step = 4;
    this.messageValue = "";
    this.messageType = "approval";
    this.dialogTitle = "Approval Message";
    this.openDialog();
  }

  openRejectMessage() {
    this.step = 5;
    this.messageValue = "";
    this.messageType = "reject";
    this.dialogTitle = "Reject Message";
    this.openDialog();
  }

  submitMessage(validate: boolean) {
    if (validate) {
      this.$Swal.fire({
        position: "center",
        icon: "success",
        title: "success",
        showConfirmButton: false,
        timer: 1500,
      });
      this.closeDialog();
    }
  }

  created() {
    this.getQuoteList();
  }

  destroyed() {
    this.$store.commit("QuotationStore/setQuote", null);
    this.$store.commit("QuotationStore/setQuoteDetails", null);
  }
}
</script>
<style lang="scss">
@import "./index.scss";
</style>
